#include "image_browser.h"
#include "convert.h"

#include <QDebug>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QToolButton>

#include <opencv2/imgcodecs.hpp>

ImageBrowser::ImageBrowser(QWidget *parent) : QWidget(parent)
{
    auto lineEdit = new QLineEdit(this);
    lineEdit->setToolTip(tr("Click to choose image file"));
    auto btn = new QToolButton(this);
    btn->setText("...");
    auto imageLabel = new QLabel(this);

    auto load_image = [=](const QString &fileName) {
        if (!fileName.isEmpty()) {
            lineEdit->setText(fileName);
//            auto mat = cv::imread(fileName.toStdString());
//            imageLabel->setPixmap(QPixmap::fromImage(cvMat2QImage(mat)));
            //or
            imageLabel->setPixmap(QPixmap::fromImage(QImage(fileName)));

        }
    };


    load_image(":/assets/images/lena.jpg");

    connect(btn, &QToolButton::clicked,
            this, [=](){
        QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                        "/home",
                                                        tr("Image (*.bmp *dib *.jpeg *.jpg *.jpe *.jp2 *.png *.webp *.pbm *.pgm *.ppm *.pxm *.pnm *.sr *.ras *.tiff *.tif *.exr *.hdr *.pic)"));
        load_image(fileName);
    });


    auto h = new QHBoxLayout();
    h->addWidget(new QLabel(tr("Image:"), this));
    h->addWidget(lineEdit);
    h->addWidget(btn);


    auto v = new QVBoxLayout(this);
    v->addLayout(h);
    v->addWidget(imageLabel, 1);
}
